import {
  Card,
  Breadcrumb,
  Form,
  Input,
  //  Select,
  Modal,
  Radio,
  message,
  Button,
  Upload,
} from "antd"
import { HomeOutlined, PlusOutlined } from "@ant-design/icons"
import styles from "./index.module.scss"
// import { useSelector } from "react-redux"
import { useEffect, useRef, useState } from "react"
import Channels from "@/compontes/Channels"
import ReactQuill from "react-quill"
import "react-quill/dist/quill.snow.css"
import {
  editArticle,
  getArticleInfo,
  saveArticle,
} from "../../store/actions/article"
import { useDispatch } from "react-redux"
import { useHistory, useParams } from "react-router-dom"
const Publish = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const { articleId } = useParams()
  //从redux中获取article文章详情
  //限制数量
  const [type, setType] = useState(1)

  //预览图片弹窗
  const [isModalOpen, setIsModalOpen] = useState(false)
  //预览图片
  const [previewImage, setPreviewImage] = useState("")

  // 上传文件列表
  const [fileList, setFileList] = useState([
    {
      uid: "-1",
      name: "image.png",
      status: "done",
      url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
    },
  ])

  //1.创建ref对象用来存储已上传的图片
  const fileRef = useRef(fileList)
  const formRef = useRef(null)

  //改变封面数量
  const onTypeChange = (e) => {
    console.log("radio checked", e.target.value)
    const count = e.target.value
    setType(count)
    setFileList(fileRef.current.slice(0, count))
  }

  //改变上传文件
  const handleFileChange = ({ fileList }) => {
    setFileList(fileList)
    fileRef.current = fileList
    //触发表单验证，设置 recursive 时会递归校验所有包含的路径(nameList?: NamePath[], config?: ValidateConfig) => Promise
    //NamePath: string | number | (string | number)[]
    formRef.current.validateFields(["cover"])
  }

  //封装添加文章的方法
  const add = async (draft, values) => {
    const images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const data = {
      ...values,
      cover: {
        type,
        images,
      },
    }
    if (articleId) {
      try {
        await dispatch(
          editArticle(draft, {
            ...data,
            articleId,
          })
        )
        message.success("修改成功")
      } catch (error) {
        console.log("error", error)
      }
    } else {
      console.log("接口需要的数据格式：", data)
      try {
        await dispatch(saveArticle(draft, data))
        message.success("发布成功")
      } catch (error) {
        console.log("error", error)
      }
    }
    history.push("/home/article")
  }

  //完成表单提交发布文章
  const onFinish = async (values) => {
    // console.log("Success:", values)
    // const { cover, ...argument } = values
    // const data = {
    //   ...argument,
    //   cover: {
    //     type: cover,
    //     images: fileList,
    //   },
    // }
    // console.log("接口需要的数据格式：", data)
    // try {
    //   await dispatch(saveArticle(data))
    //   message.success("发布成功", 1, () => {
    //     history.push("/home/article")
    //   })
    // } catch (error) {
    //   console.log("error", error)
    // }
    add(false, values)
  }

  //存入草稿
  const addDraft = async () => {
    // 1. `getFieldsValue()` 仅获取表单数据，不进行表单校验
    // 2. `validateFields()` 先进行表单校验，再获取表单数据【此处，使用该方法】
    //先进行表单校验，再获取表单数据
    try {
      const values = await formRef.current.validateFields()
      add(true, values)
    } catch (error) {}
  }
  //提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    return message.warning(errorInfo.errorFields[0].errors[0])
  }
  //上传组件的图片预览
  const onPreview = (file) => {
    setIsModalOpen(true)
    setPreviewImage(file.url || file.response.data.url)
  }
  //关闭Modal弹窗
  const handleCancel = () => {
    setIsModalOpen(false)
  }
  //编辑文章-数据回显
  useEffect(() => {
    if (!articleId) return
    // 如果有id，代表是修改
    dispatch(getArticleInfo(articleId)).then((res) => {
      console.log("res741", res)
      formRef.current.setFieldsValue({
        ...res,
        cover: res.cover.type,
      })
      // 图片的回显
      setType(res.cover.type)
      const list = res.cover.images.map((item) => {
        return {
          url: item,
        }
      })
      setFileList(list)
      fileRef.current = list
    })
  }, [articleId, dispatch])

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb
            items={[
              {
                href: "/home",
                title: (
                  <>
                    <HomeOutlined />
                    <span>首页</span>
                  </>
                ),
              },
              {
                title: articleId ? "编辑文章" : "发布文章",
              },
            ]}
          ></Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          size="large"
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            cover: 1,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: "请输入文章的标题!",
              },
            ]}
          >
            <Input style={{ width: 400 }} placeholder="请输入文章的标题" />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: "请输选择频道!",
              },
            ]}
          >
            {/* <Select style={{ width: 200 }} allowClear placeholder="请选择频道">
              {channels.map((item) => (
                <Select.Option key={item.articleId} value={item.name}>
                  {item.name}
                </Select.Option>
              ))}
            </Select> */}
            <Channels />
          </Form.Item>

          <Form.Item
            label="封面"
            name="cover"
            rules={[
              {
                validator(_, value) {
                  if (fileList.length !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Radio.Group onChange={onTypeChange} value={type}>
              <Radio value={1}>单面</Radio>
              <Radio value={3}>三面</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="上传图片">
            {/* 
              filelist: 控制上传图片
              action: 上传的地址
              name:  上传的文件的名字默认file
            */}
            <Upload
              listType="picture-card"
              fileList={fileList}
              name="image"
              action={"http://geek.itheima.net/v1_0/upload"}
              onChange={handleFileChange}
              maxCount={type}
              onPreview={onPreview}
            >
              {fileList.length < type && <PlusOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: "请输内容!",
              },
            ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ "margin-right": "20px" }}
            >
              {articleId ? "编辑" : "发布"}文章
            </Button>
            <Button onClick={addDraft}>存入草稿</Button>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        title="图片预览"
        width={800}
        open={isModalOpen}
        footer={null}
        // onOk={handleOk}
        onCancel={handleCancel}
      >
        <div style={{ textAlign: "center" }}>
          <img src={previewImage} style={{ width: 600 }} alt="" />
        </div>
      </Modal>
    </div>
  )
}

export default Publish
